//
//  NSString+FileSize.m
//  TravelGuideMdd
//
//  Created by 陈曦 on 13-6-4.
//  Copyright (c) 2013年 mafengwo.com. All rights reserved.
//

#import "NSString+FileSize.h"

@implementation StringFileSizeItem
@end

StringFileSizeItem* StringFileSizeItem_(unsigned long long size,
                                        unsigned long long levelSize,
                                        NSString *str)
{
    __autoreleasing StringFileSizeItem *item = [[StringFileSizeItem alloc] init];
    item.size = size;
    item.str = str;
    item.levelSize = levelSize;
    return item;
}

@implementation NSString(FileSize)

+ (NSString*)stringByFileSize:(unsigned long long)aFileSize
{
    
    NSArray *arr = @[
                     StringFileSizeItem_(KBSIZE / 2, 1      , @"B"),
                     StringFileSizeItem_(MBSIZE / 2, KBSIZE , @"KB"),
                     StringFileSizeItem_(GBSIZE / 2, MBSIZE , @"MB"),
                     StringFileSizeItem_(TBSIZE / 2, GBSIZE , @"GB"),
                     StringFileSizeItem_(-1ull,         TBSIZE , @"TB")
                     ];
    
    return [NSString stringByFileSize:aFileSize withItemArr:arr];
}

+ (NSString*)stringByFileSize:(unsigned long long)aFileSize withItemArr:(NSArray *)arr
{
    for (NSUInteger i = 0 ; i< arr.count ; i++)
    {
        StringFileSizeItem *item = [arr objectAtIndex:i];
        if (aFileSize < item.size)
        {
            if (item.levelSize == 1 || item.levelSize == 0)
            {
                return [NSString stringWithFormat:@"%lld%@",aFileSize,item.str];
            }
            else
            {
                return [NSString stringWithFormat:@"%.2f%@",aFileSize * 1.0 / item.levelSize,item.str];
            }
        }
    }
    return [NSString stringWithFormat:@"%.2fGB",aFileSize / 1024.0 / 1024.0 / 1024.0];
}

@end
